你可能會問:「不是要學 Flutter 嗎?為什麼要先學 Dart?」
你可以把 Flutter 想像成是一套精美的樂高積木(Widgets),Dart 就是用來組合這些積木的「說明書」與「規則」。如果你能看得懂規則,在組合積木時自然會得心應手、事半功倍。
今天,我們不會深入 Dart 的所有細節,而是會「速成教學」,專注那些在 Flutter 開發中較常用到的核心語法。我們的目標是:當明天看到 Flutter 程式碼時,不會感到陌生。
本日最佳夥伴:DartPad
今天的所有範例,都可以在 DartPad 這個官方線上編輯器中直接執行,完全不需要本機環境,非常方便!
main
開始main()
函式。// 這是程式的進入點
void main() {
// 使用 print() 在控制台印出文字
print('Hello, Dart!');
}
void main() {
// var Dart 會自動推斷型別
var name = '省錢拍拍'; // string (字串)
// 當然也可以明確指定型別
int version = 1; // int(整數)
double rating = 4.5; // double (浮點數)
bool isReleased = true; // bool (布林值)
// final: 只能賦值一次,可以在「執行時期」決定
final DateTime now = DateTime.now();
print('現在時間: $now');
// const: 必須在「編譯時期」就確定,不能依賴執行結果
const double PI = 3.14159;
// ⚠️ const 無法使用執行時才能得到的值
// const DateTime today = DateTime.now(); // ❌ 會報錯
}
final | const | |
---|---|---|
賦值時機 | 執行時期 (Runtime) | 編譯時期 (Compile-time) |
特性 | 只能賦值一次 | 編譯期常數,更嚴格 |
範例 | final time = DateTime.now(); | const PI = 3.14; |
void main() {
// 1. 不可為空 (一定要給初始值)
// String title; // 這行會報錯,因為沒有給初始值
String title = "Flutter Null Safety";
double price = 99.9;
bool isAvailable = true;
print('Product Title: $title');
print('Price: $price');
print('Available: $isAvailable');
// 2. 可為空 (nullable, 預設是 null)
// 如果一個變數「有可能」是空的,在型別後面加上 ?
String? subtitle;
double? discount;
bool? isLoggedIn;
print('Subtitle: ${subtitle ?? "Not set"}');
print('Discount: ${discount ?? 0.0}');
print('Is logged in: ${isLoggedIn ?? false}');
}
要注意如果看到 ? 就表示「這個值可能是 null」,要謹慎處理。
void main() {
// 建立一個 List
List<String> fruits = ['Apple', 'Bannna', 'Orange'];
//新增元素
fruits.add('Mango');
//存取元素 (按照索引)
print(fruits[0]); // Apple
// 修改元素
fruits[1] = 'Blueberry';
// 迭代 List
for (var fruit in fruits) {
print(fruit);
}
// 建立一個 Map
Map<String, int> scores = {'Alice': 90, 'Bob': 85, 'Charlie': 92};
// 新增或更新 Key-Value
scores['David'] = 88;
scores['Alice'] = 95; // 更新 Alice 的分數
// 取值(透過 key
print(scores['Alice']); // 95
// 檢查是否存在某個 key
print(scores.containsKey('Bob')); // true
// 迭代 Map
scores.forEach((key, value) {
print('$key: $value');
});
}
// 1. 基本函式
// 沒有回傳值
void printMessage(String message) {
print('Message: $message');
}
// 有回傳值
int add(int a, int b) {
return a + b;
}
// 箭頭函式 (簡化單行函式)
int multiply(int a, int b) => a * b;
// 2. 選擇性參數
// 位置型參數 []
void greet(String name, [String? message]) {
print('Hello $name, ${message ?? "歡迎!"}');
}
// 命名參數 {}
void greetUser({required String name, int age = 18}) {
print("Name: $name, Age: $age");
}
// 3. 函式作為參數
void doOperation(int a, int b, int Function(int, int) operation) {
print("結果: ${operation(a, b)}");
}
// 程式主入口
void main() {
print("--- 基本函式 ---");
printMessage("學習 Dart 函式");
print("add(5, 3) = ${add(5, 3)}");
print("multiply(5, 3) = ${multiply(5, 3)}");
print("\n--- 選擇性參數 ---");
greet("Alice");
greet("Bob", "今天天氣真好");
greetUser(name: "Charlie");
greetUser(name: "David", age: 30);
print("\n--- 函式作為參數 ---");
doOperation(5, 3, add); // 結果: 8
doOperation(5, 3, multiply); // 結果: 15
// 傳入匿名函式
doOperation(5, 3, (x, y) => x - y); // 結果: 2
}
// 定義一個 Idea 類別
class Idea {
// 類別的屬性 (Properties)
String title;
String content;
bool isFavorite;
// 這是建構子 (Constructor),用來建立物件
// this.title 的寫法是個語法糖,代表將傳入的 title 賦值給類別的 title 屬性
Idea(this.title, this.content, {this.isFavorite = false});
// 類別的方法 (Methods)
void display() {
print('Title: $title');
print('Content: $content');
print('Favorite: $isFavorite');
}
}
void main() {
// 透過類別建立一個 idea 物件 (Object)
var myIdea = Idea(
'My Awesome App',
'An app that connects people.',
isFavorite: true,
);
// 呼叫方法
myIdea.display();
}
✅ 重點:
說要放緩腳步,結果文章也默默地超過了兩千字,今天我們快速瀏覽了 Dart 的核心語法,從變數、函式到重要的類別。讀者可以親手在 DartPad 上敲一遍範例,加深印象。
不需要立刻記住所有細節,只需要有一個初步的認識即可,有了這些基礎,當我們明天開始拆解 Flutter 專案時,就不會顯得特別陌生。
明天,將創建「省錢拍拍 (SnapSaver)」專案,並深入了解 Flutter 專案的結構與 Widget 的核心概念。
那就明天見!